package com.gnerv.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gnerv.cms.common.CommonParam;
import com.gnerv.cms.entity.Catalog;
import com.gnerv.cms.mapper.CatalogMapper;
import com.gnerv.cms.service.ICatalogService;
import com.gnerv.cms.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * CMS平台-栏目表 服务实现类
 * </p>
 *
 * @author Gnerv LiGen
 * @since 2019-07-01
 */
@Service
public class CatalogServiceImpl extends ServiceImpl<CatalogMapper, Catalog> implements ICatalogService {

    @Autowired
    CatalogMapper catalogMapper;

    @Override
    public boolean createCatalog(Catalog catalog) {
        catalog.setbId(UUIDUtil.getLower());
        catalogMapper.insert(catalog);
        return true;
    }

    @Override
    public boolean deleteCatalog(String bId) {
        catalogMapper.delete(new QueryWrapper<>(new Catalog(bId)));
        return true;
    }

    @Override
    public boolean updateCatalog(Catalog catalog) {
        catalogMapper.update(catalog, new QueryWrapper<>(new Catalog(catalog.getbId())));
        return true;
    }

    @Override
    public Catalog selectCatalog(String bId) {
        Catalog catalog = catalogMapper.selectOne(new QueryWrapper<>(new Catalog(bId)));
        return catalog;
    }

    @Override
    public List<Catalog> listCatalog(Catalog catalog) {
        List<Catalog> catalogs = catalogMapper.selectList(new QueryWrapper<>(catalog));
        return catalogs;
    }

    @Override
    public boolean bindingArticle(String cId, String aId) {
        int i = catalogMapper.checkBingding(cId, aId);
        if (i == CommonParam.I_ZERO) {
            catalogMapper.bindingArticle(cId, aId);
        }
        return true;
    }

    @Override
    public boolean relieveArticle(String aId) {
        catalogMapper.relieveArticle(aId);
        return true;
    }

    @Override
    public List<Catalog> selectCatalogTree(String bId) {
        List<Catalog> catalogs = new ArrayList<>();
        if (CommonParam.S_ZERO.contentEquals(bId)) {
            catalogs = catalogMapper.selectCatalogTree(bId);
            return catalogs;
        } else {
            Catalog catalog = catalogMapper.selectOne(new QueryWrapper<>(new Catalog(bId)));
            List<Catalog> childOrgTrees = catalogMapper.selectCatalogTree(bId);
            catalog.setChildren(childOrgTrees);
            catalogs.add(catalog);
            return catalogs;
        }
    }
}
